package com.sys.console.cookie;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sys.console.business.SysUserService;
import com.sys.console.pojo.Sys_User;
import com.sys.object.common.context.ServiceInitContainer;
import com.sys.object.common.utils.MyStringUtils;


/**
 * 使用Cookie实现。Cookie的格式为：
 * 1， 名称：LINGDONG_COOKIE
 * 2， 值：{userId}_{userpw}_{userregmail}_{验证}_{失效日期的毫秒表示}
 */
public class UserLogonCookieUtils {
	
	private static Log log = LogFactory.getLog(UserLogonCookieUtils.class);
	
	/**
	 * 向浏览器发送自动登录的Cookie
	 * 
	 * @param member
	 * @param autoLoginDays 自动登录的时间，单位：天。
	 * @param response
	 */
	public static void addAutoLoginCookie(Sys_User user, int autoLoginDays, HttpServletResponse response) {
		//系统设置安全key
		String key = Constant_Cookie.SAFE_KEY;
		//写入cookie生存时间
		long expirationTime = autoLoginDays * (long) 24 * 3600 * 1000 + System.currentTimeMillis();
		String cookieValidate = DigestUtils.md5Hex(user.getUsername() + user.getPassword() + key);
		//考虑cookie的伪造，保证其他用户无法猜解出cookie的值
		//加密字符串为用户名及用户密码的md5 加密
		String autoLoginAuthKey = user.getUid() + 
									"_" + user.getUsername()+ 
									"_" + user.getPassword()+ 
									"_" + cookieValidate + 
									"_" + expirationTime;
		
		// 发送Cookie
		String cookieName = Constant_Cookie.COMPANY_COOKIE;
		String cookieValue = MyStringUtils.base64Encoder(autoLoginAuthKey);//base64加密
		Integer cookieAge = (int) autoLoginDays * 24 * 3600;
		
		CookieUtils.addCookie(response, cookieName, cookieValue, cookieAge);
	}
	
	public static void addWebAutoLoginCookie(Sys_User user, int autoLoginDays, HttpServletResponse response) {
		//系统设置安全key
		String key = Constant_Cookie.SAFE_KEY;
		//写入cookie生存时间
		long expirationTime = autoLoginDays * (long) 24 * 3600 * 1000 + System.currentTimeMillis();
		String cookieValidate = DigestUtils.md5Hex(user.getUsername() + user.getPassword() + key);
		//考虑cookie的伪造，保证其他用户无法猜解出cookie的值
		//加密字符串为用户名及用户密码的md5 加密
		String autoLoginAuthKey = user.getUid() + 
									"_" + user.getUsername()+ 
									"_" + user.getPassword()+ 
									"_" + cookieValidate + 
									"_" + expirationTime;
		
		// 发送Cookie
		String cookieName = Constant_Cookie.COMPANY_COOKIE;
		String cookieValue = MyStringUtils.base64Encoder(autoLoginAuthKey);//base64加密
		Integer cookieAge = (int) autoLoginDays * 24 * 3600;
		
		CookieUtils.addCookie(response, cookieName, cookieValue, cookieAge);
	}

	/**
	 * 检查自动登录，如果符合自动登录的条件，就登录用户。
	 * 
	 * @param request
	 * @param userService
	 */
	public static boolean tryAutoLogin(HttpServletRequest request) {

		// 如是没有自动登录的Cookie，返回
		String cookie = CookieUtils.getCookieByName(request, Constant_Cookie.COMPANY_COOKIE);
				
		if (cookie == null) {
			return false;
		}

		// 检测自动登录。如果cookie的值与我们的生成规则一致的话登录
		try {
			// cookie 解密
			String s = MyStringUtils.base64Decoder(cookie);
		
			String[] valueTokens = s.split("_");
			// 获取用户
			String userId = valueTokens[0];	
			Sys_User cmsuser = new Sys_User();
			cmsuser.setUid(Integer.parseInt(userId));
			cmsuser.setUsername(valueTokens[1]);
			cmsuser.setPassword(valueTokens[2]);
			SysUserService sysUserService = (SysUserService) ServiceInitContainer.mapperMap.get("sysUserService");
			Sys_User user = sysUserService.selectByAutoLogin(cmsuser);
			if (user != null && 
					valueTokens.length == 5 &&
					valueTokens[3].equals(DigestUtils.md5Hex(valueTokens[1] + valueTokens[2] + Constant_Cookie.SAFE_KEY)) ) {
				
				long expirationTime = Long.parseLong(valueTokens[4]);
				//
				//initUserAuthority();
				// 检测cookie是否过期
				if (System.currentTimeMillis() < expirationTime) { 
					WebUtils.login(user,request);
				}
				
				return true;
			}
			return false;

		} catch (Exception e) {
			log.warn("自动登录失败，【cookie.value=" + cookie + "】，相关异常信息为：" + e.getMessage());
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 通知浏览器删除自动登录的Cookie。
	 * 
	 * @param response
	 * @param user
	 */
	public static void delAutoLoginCookie(HttpServletResponse response, Sys_User user) {
		// 1，保存到客户端(发送Cookie)
		String cookieName = Constant_Cookie.COMPANY_COOKIE;
		String cookieValue = "";
		Integer cookieAge = 0;
		// add cookie
		CookieUtils.addCookie(response, cookieName, cookieValue, cookieAge);
	}
}
